﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OL_LogTableInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters { get; set; }
        public Base_InterfaceOption queryOption { get; set; }
        //public Base_InterfaceOption insertOption { get; set; }
        //public Base_InterfaceOption upDateOption { get; set; }
        //public Base_InterfaceOption deleteOption { get; set; }

        public List<Base_ConfigParameter> WorkSheetList { get; set; }

        public OL_LogTableInterfaceBusiness()
        {
            this.InterfaceName = "OL备份日志业务表";
            //获取字段的映射关系
            tableField = GetMapField("getFilterRows");
            //索引字段
            Keys = GetKeys("getFilterRows");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();

            //数据库连接
            this.ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            this.SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            this.queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            //this.insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
            //this.upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
            //this.deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

            this.WorkSheetList = new List<Base_ConfigParameter>();

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //只设置一次的参数
            queryEventArgs.Page.WorksheetId = WorkSheetList[0].Value;
            if (!queryEventArgs.Page.SetFlag)
            {
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "pageSize").First().SourceField.ToInt();
                queryEventArgs.Page.SetFlag = true;
                //执行查询前添加过滤条件
                if (!Filters.IsNullOrEmpty()) queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();


            //单个工作表是否查询完成
            if (queryEventArgs.Success)
            {
                //向源数据中添加额外的信息
                List<JToken> jTokens = queryEventArgs.Result["data"]["rows"].ToList();
                jTokens.ForEach(row =>
                {
                    var newObj = JObject.FromObject(row); // 将现有token转换为JObject
                    newObj.Add("tableName", WorkSheetList[0].Describe); // 添加新字段
                    newObj.Add("workSheetId", WorkSheetList[0].Value); // 添加新字段
                    queryEventArgs.Rows.Add(newObj);
                });
                //获取总页数
                queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();


                //单个表的数据查询完成，移除第一个表，继续查询下一个表
                if (queryEventArgs.Result["data"]["rows"].ToList().Count < queryEventArgs.Page.PageSize)
                {
                    //移除第一个表，继续查询其他表
                    WorkSheetList.RemoveAt(0);
                    queryEventArgs.Page.PageIndex = 0;
                }
                //判断所有表是否查询完成
                if (WorkSheetList.IsNullOrEmpty() || WorkSheetList.Count == 0) queryEventArgs.Page.Complete = true;

            }


        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async Task<List<OL_LogTable>> ExecuteInterface()
        {
            List<OL_LogTable> rows = new List<OL_LogTable>();
            try
            {
                //获取需要备份的所有表ID
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var sheet = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='OneLink_LogTable'");
                //是否需要单独新增个别表的日志，如果是则更新个别表，否则更新全部
                var sheet1 = sheet.Where(x => x.Type == "Y");
                WorkSheetList = !sheet1.IsNullOrEmpty() && sheet1.Count() > 0 ? sheet1.ToList() : sheet;

                if (WorkSheetList.Count > 0)
                {
                    //获取需要更新的时间段
                    var totle = queryOption.ExcInterval;
                    //查询条件

                    Filters.Clear();
                    //只获取更新时间为当天的行还是所有行
                    if (totle==-1)
                    {
                        Filters.Add(
                            new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 17, Value = "" }
                        );
                    }
                    else
                    {

                        Filters.Add(
                            new OL_FilterDTO() { ControlId = "utime", DataType = 15, SpliceType = 1, FilterType = 14, Value = DateTime.Now.AddDays(-totle).ToString("yyyy-MM-dd") }
                        );
                    }

                    //执行查询
                    rows = await QueryAsync<OL_LogTable>(queryOption, tableField, SqlDb);
                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

            return rows;
        }

        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row_Update<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }
        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
